<!DOCTYPE html>
<html lang="en">

<head>
    <link rel="stylesheet" type="text/css" href="css/reset.min.css">
    <title>PDF转图片工具</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
            text-align: center;
        }

        .header {
            display: flex;
            justify-content: center;
            align-items: center;
            margin: 20px;
        }

        h1 {
            font-size: 24px;
            margin: 0 auto 0 auto;
        }

        .toolbox-link {
            position: absolute;
            top: 20px;
            right: 20px;
        }

        label {
            font-size: 16px;
            margin-right: 5px;
        }

        input[type="file"] {
            display: none;
        }

        .custom-file-upload {
            display: inline-block;
            padding: 8px 16px;
            font-size: 16px;
            border: none;
            border-radius: 3px;
            background-color: #007bff;
            color: #fff;
            cursor: pointer;
        }

        .image-container {
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
            margin-top: 20px;
        }

        .image-container img {
            max-height: 300px;
            margin: 5px;
            object-fit: cover;
            transition: transform 0.3s ease;
        }

        .image-container img:hover {
            transform: scale(2);
        }

        .img-box {
            width: 90%;
            min-width: 1000px;
            border: 1px solid #ccc;
            border-radius: 10px;
            margin: 20px auto;
            padding: 20px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
            background-color: #fff;
            color: gray;
            font-weight: bolder;
            font-size: 18px;
        }

        button {
            padding: 8px 16px;
            font-size: 16px;
            border: none;
            border-radius: 3px;
            background-color: #007bff;
            color: #fff;
            cursor: pointer;
        }

        button:disabled {
            background-color: #ccc;
            cursor: not-allowed;
        }
    </style>
</head>

<body>
    <div class="header">
        <h1>PDF转图片工具</h1>
        <a href="/" class="toolbox-link">
            < 返回工具箱</a>
    </div>
    <label for="pdfFile">选择PDF文件：</label>
    <button onclick="openFileSelector()">选择PDF文件</button>
    <label style="display: block; font-size: 10px; color: red; padding: 10px 0 0 15px;">*大文件可能会花费数分钟的时间，请耐心等待。</label>
    <div class="img-box">
        <div id="statusLabel">转换后的图片</div>
        <div class="image-container" id="resultContainer"></div>
    </div>
    <button onclick="downloadResultImages()" id="downloadResultImages" disabled>下载JPG图片</button>

    <script>
        function openFileSelector() {
            fetch('/clear-pdf-cache')
                .then(function (response) {
                    return response.text();
                })
                .then(function (message) {
                    console.log(message);
                    var input = document.createElement('input');
                    input.type = 'file';
                    input.accept = '.pdf'; // 只允许选择PDF文件
                    input.addEventListener('change', function (event) {
                        var files = event.target.files; // 获取选择的文件列表
                        convertToImages(files); // 调用转换为图片的函数
                    });
                    input.click();
                })
                .catch(function (error) {
                    console.error('Clear image cache error:', error);
                });
        }

        function convertToImages(files) {
            var formData = new FormData();
            for (var i = 0; i < files.length; i++) {
                var file = files[i];
                var encodedFileName = encodeURIComponent(file.name);
                formData.append('pdfFile', file, encodedFileName);
            }

            // 执行状态
            var statusLabel = document.getElementById('statusLabel');
            statusLabel.textContent = '图片提取中';
            var dots = 1;
            var timer = setInterval(function () {
                statusLabel.textContent = '图片提取中' + '.'.repeat(dots);
                dots = (dots + 1) % 4;
            }, 500);

            // 发送POST请求上传PDF文件
            fetch('/pdf-to-images', {
                method: 'POST',
                body: formData,
            })
                .then(function (response) {
                    return response.json();
                })
                .then(function (result) {
                    // 处理转换结果
                    console.log(result);
                    displayProcessedImages(result.images);
                    // 清除执行状态
                    clearInterval(timer);
                    statusLabel.textContent = '转换后的图片';
                })
                .catch(function (error) {
                    // 清除执行状态
                    clearInterval(timer);
                    statusLabel.textContent = '转换后的图片';
                    console.error('PDF upload error:', error);
                });
        }

        async function displayProcessedImages(images) {
            var resultContainer = document.getElementById('resultContainer');
            resultContainer.innerHTML = '';

            try {
                var promises = images.map(function (imageUrl) {
                    return new Promise(function (resolve, reject) {
                        var img = document.createElement('img');
                        img.onload = function () {
                            img.classList.add('processed-image');
                            resultContainer.appendChild(img);
                            resolve();
                        };
                        img.onerror = function () {
                            reject(new Error('Failed to load image: ' + imageUrl));
                        };
                        img.src = addRandomParam(imageUrl); // 避免加载到浏览器缓存
                    });
                });

                // 等待所有图片加载完成,启用下载按钮
                await Promise.all(promises);
                var downloadButton = document.getElementById("downloadResultImages");
                downloadButton.disabled = false;
            } catch (error) {
                console.error('Error:', error);
            }
        }

        // 添加随机参数到图片URL
        function addRandomParam(url) {
            var randomParam = Date.now();
            return url + '?' + randomParam;
        }

        function downloadResultImages() {
            fetch('/download-result-images')
                .then(function (response) {
                    return response.blob();
                })
                .then(function (blob) {
                    var timestamp = Date.now();
                    var link = document.createElement('a');
                    link.href = URL.createObjectURL(blob);
                    link.download = 'PDF转JPG_' + timestamp + '.zip';
                    link.click();
                    URL.revokeObjectURL(link.href);
                })
                .catch(function (error) {
                    console.error('Download images error:', error);
                });
        }
    </script>
</body>

</html>